package com.ciwong.epaper.modules.epaper.ui.newlistenspeak.longcoversation;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.dbbean.AnswerContent;
import com.ciwong.epaper.modules.dbbean.LswAnswer;
import com.ciwong.epaper.modules.epaper.bean.Attachments;
import com.ciwong.epaper.modules.epaper.bean.ModuleSet;
import com.ciwong.epaper.modules.epaper.bean.OptionDetail;
import com.ciwong.epaper.modules.epaper.bean.OptionInfo;
import com.ciwong.epaper.modules.epaper.bean.QuestionScore;
import com.ciwong.epaper.modules.epaper.bean.Questions;
import com.ciwong.epaper.modules.epaper.bean.ResourceDetail;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.widget.ScaleScreenImageView;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.ciwong.mobilelib.utils.BaseUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageSize;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2017/2/13.
 */
public class LongCoversataionQuestionLayout extends LinearLayout {


	private final String TAG = "QuestionLayout";
	protected TextView     tvTitle;// 问题标题
	private   TextView     tvBigStem;//大题标题
	public    LinearLayout mChildLayoutContainer;// 小题标题
	protected TextView     tvStem;
	protected WebView      webViewSmallStem;
	public    LinearLayout imgContainer, llStemContainer;
	//用于上个选择的选项，选中新选项，旧选中选项复位--neo 2017/3/11
	protected View oldSelectedView = null;

	protected String[] optionHeads = new String[]{"A", "B", "C", "D", "E", "F",
			"G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
			"T", "U", "V", "W", "X", "Y", "Z"};

	protected int checkedIndex = -1;

	protected OptionInfo checkedOptionInfo = null;// 用户选中的选项

	private boolean mAllowAnswer = false;


	private View bg_big_stem;
	private View bg_question_content;

	private View root_question_layout;
	private ResourceDetail mResourceDetail;
	private String mUuid;

	public LongCoversataionQuestionLayout(Context context) {
		this(context, null);
	}

	public LongCoversataionQuestionLayout(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public LongCoversataionQuestionLayout(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		LayoutInflater.from(this.getContext()).inflate(R.layout.listen_speak_long_conversation_question_layout, this);
		initView();
	}

	private void initView() {
		tvTitle = (TextView) findViewById(R.id.question_title);// 问题标题

		tvBigStem = (TextView) findViewById(R.id.big_question_stem);// 大题题干
		tvStem = (TextView) findViewById(R.id.small_question_stem_tv);// 小题题干

		webViewSmallStem = (WebView) findViewById(R.id.small_question_stem);// 小题题干
		webViewSmallStem.getSettings().setDefaultTextEncodingName("utf-8");
		webViewSmallStem.getSettings().setSavePassword(false);
		webViewSmallStem.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
		webViewSmallStem.setVerticalScrollBarEnabled(false);
		webViewSmallStem.setVerticalScrollbarOverlay(false);
		webViewSmallStem.setHorizontalScrollBarEnabled(false);
		webViewSmallStem.setHorizontalScrollbarOverlay(false);
		webViewSmallStem.setBackgroundColor(0);

		imgContainer = (LinearLayout) findViewById(R.id.img_container);
		llStemContainer = (LinearLayout) findViewById(R.id.ll_stem);

		mChildLayoutContainer = (LinearLayout) findViewById(R.id.child_question_layout_container);// 子题布局

		bg_big_stem = findViewById(R.id.bg_big_stem);
		bg_question_content = findViewById(R.id.bg_question_content);
		root_question_layout = findViewById(R.id.root_question_layout);
	}


	/**
	 * 考试开始预先加载大题和选项
	 */
	public void initBigQuestionAndOptions(ResourceDetail resourceDetail, int bigQuesIndex, int smallQuesIndex) {
		ModuleSet moduleSet = resourceDetail
				.getTemplateSettings();
		// 设置大题题干  切换问题标题
		setBigQuesStem(moduleSet.getContent(), bigQuesIndex, smallQuesIndex);
	}

	/**
	 * 设置大题题干内容
	 *
	 * @param text
	 */
	public void setBigQuesStem(String text, int BigQuesIndex, int SmallQuesIndex) {
		changeQuestionTitle(BigQuesIndex, SmallQuesIndex);
		if (TextUtils.isEmpty(text)) {
			tvBigStem.setVisibility(View.GONE);
		} else {
			tvBigStem.setText(text);
			tvBigStem.setVisibility(View.VISIBLE);
		}
	}


	/**
	 * 加载小题题干
	 * 包括纯文本和富文本
	 *
	 * @param text
	 */
	public void setSmallQuestionStem(String text) {
		if (TextUtils.isEmpty(text)) {
			//加载含有H5标题
			webViewSmallStem.setVisibility(View.GONE);
			//加载纯文本标题
			tvStem.setVisibility(View.GONE);

		} else {

			if (text.contains("<table") || text.contains("<img") || text.contains("{#blank#}")) {
				String textValue = ListenSpeakUtil.addHtmlHead(text);
				webViewSmallStem.loadDataWithBaseURL(null, textValue,
						"text/html; charset=utf-8", "utf-8", null);
				webViewSmallStem.setVisibility(View.VISIBLE);
				tvStem.setVisibility(View.GONE);
			} else {
				tvStem.setText(text);
				tvStem.setVisibility(View.VISIBLE);
				webViewSmallStem.setVisibility(View.GONE);
			}
		}
	}

	/**
	 * 切换问题标题
	 */
	public void changeQuestionTitle(int BigQuesIndex, int SmallQuesIndex) {
		tvTitle.setText(getContext().getString(R.string.question_title, BaseUtils.formatInteger(BigQuesIndex + 1), String.valueOf(SmallQuesIndex + 1)));
	}

	public void setTitleVisibility(int visibility) {
		tvTitle.setVisibility(visibility);
	}


	/**
	 * 显示图片
	 *
	 * @param imgUrl
	 */
	public void showImg(final String imgUrl, final int index,
	                    final List<String> imgList) {
		final ScaleScreenImageView itemImg = (ScaleScreenImageView) View
				.inflate(getContext(),
						R.layout.item_listen_speak_img, null);
		itemImg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				BaseJumpManager.jumpToScanImage((Activity) getContext(),
						R.string.listen_speak, new ArrayList<String>(imgList),
						index);
			}
		});
		ImageSize size = new ImageSize(DeviceUtils.getScreenWdith(),
				R.dimen.word_pic_height);
		if (itemImg != null) {
			itemImg.setImageBitmap(ImageLoader.getInstance().loadImageSync(imgUrl, size));
		}

		imgContainer.setVisibility(View.VISIBLE);
		imgContainer.addView(itemImg);

	}

	public void imgContainerRemoveAllViews() {
		imgContainer.removeAllViews();
	}

	public void imgContainerSetVisibility(int visibility) {
		imgContainer.setVisibility(visibility);
	}

	public void reSetCheckedIndex(int index) {
		checkedIndex = index;
	}

	/**
	 * 开始加载图片
	 *
	 * @param optionsDetail
	 */
	public void startLoadImg(OptionDetail optionsDetail, View seekBar) {
		// 取附件集合
		final List<Attachments> attachmentsList = optionsDetail
				.getAttachments();
		List<String> imgUrlList = new ArrayList<String>();
		imgContainerRemoveAllViews();

		if (attachmentsList != null && !attachmentsList.isEmpty()) {
			for (int i = 0; i < attachmentsList.size(); i++) {
				Attachments attachments = attachmentsList.get(i);
				if (attachments != null) {
					String url = attachments.getUrl();
					if (!TextUtils.isEmpty(url)) {
						if (attachments.getFileType() == Attachments.AttachmentFileType.ATTACHMENT_FILE_TYPE_IMG) {
							url = ESystem.formatPath(url);
							imgUrlList.add(url);
							//只显示第一张
							if (imgUrlList != null && imgUrlList.size() == 1) {
								showImg(url, i, imgUrlList);
							}
						}
					}
				}
			}
		}

	}


	public void allowAnswer(boolean allowAnswer) {
		int childCount = mChildLayoutContainer.getChildCount();
		for (int i = 0; i < childCount; i++) {
			View childView = mChildLayoutContainer.getChildAt(i);
			if (childView instanceof ChildQuestionLayout) {
				ChildQuestionLayout questionLayout = (ChildQuestionLayout) childView;
				questionLayout.allowAnswer(allowAnswer);
			}

		}
	}


	public void setBigStemHighLight(boolean isStemHighLight) {
		if (isStemHighLight) {
			tvBigStem.setTextColor(getResources().getColor(R.color.black));
			bg_big_stem.setBackgroundColor(getResources().getColor(R.color.white));

			bg_question_content.setBackgroundColor(getResources().getColor(R.color.layer_bg_));
			tvStem.setTextColor(getResources().getColor(R.color.light_gray8));

		} else {
			tvBigStem.setTextColor(getResources().getColor(R.color.light_gray8));
			bg_big_stem.setBackgroundColor(getResources().getColor(R.color.layer_bg_));

			bg_question_content.setBackgroundColor(getResources().getColor(R.color.white));
			tvStem.setTextColor(getResources().getColor(R.color.black));
		}
	}


	private HashMap<String, LswAnswer> mAnswerLinkedHashMap = new HashMap<>();

	public void setChildContent(ResourceDetail resourceDetail, Questions smallQuestion, final Questions childQuestion, int childIndex, String uuid, List<LswAnswer> hasDoneAnswers, int size, final int bigQuesIndex, final int totalQuesIndex, final String quesNo) {
		mResourceDetail = resourceDetail;
		mUuid = uuid;
		LswAnswer hasDoneAnswer = null;
		if (hasDoneAnswers != null) {
			for (int i = 0; i < hasDoneAnswers.size(); i++) {
				LswAnswer lswAnswer = hasDoneAnswers.get(i);
				if (lswAnswer.getVersionId().equals(childQuestion.getVersionId())) {
					hasDoneAnswer = lswAnswer;
					break;
				}
			}
		}
		createDefaultAnswer(resourceDetail, childQuestion, uuid,bigQuesIndex,totalQuesIndex,quesNo);
		mChildLayoutContainer.setVisibility(VISIBLE);
		ChildQuestionLayout childQuestionLayout = new ChildQuestionLayout(getContext());
		childQuestionLayout.setOnChildCheckListener(new ChildQuestionLayout.OnChildCheckListener() {
			@Override
			public void onChildChecked(Questions childQuestion,String questionVersionId, String answerId, int childIndex, int indexSelected) {
				LswAnswer lswAnswer = mAnswerLinkedHashMap.get(questionVersionId);
				if (lswAnswer != null) {
					lswAnswer.setAnswer(true);
					List<AnswerContent> answerContents = lswAnswer.getAnswerContents();
					if (answerContents != null && answerContents.size() > 0) {
						answerContents.get(0).setContent(answerId);
					}
				}else{
					FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, "questionVersionId不在mAnswerLinkedHashMap中=="+mAnswerLinkedHashMap.size(), "长对话页面");
					LswAnswer defaultAnswer = createDefaultAnswer(mResourceDetail, childQuestion, mUuid,bigQuesIndex,totalQuesIndex,quesNo);
					lswAnswer.setAnswer(true);
					List<AnswerContent> answerContents = lswAnswer.getAnswerContents();
					if (answerContents != null && answerContents.size() > 0) {
						answerContents.get(0).setContent(answerId);
					}
					mAnswerLinkedHashMap.put(questionVersionId,defaultAnswer);
				}
			}
		});
		childQuestionLayout.setChildContent(childQuestion, childIndex, hasDoneAnswer,resourceDetail);
		mChildLayoutContainer.addView(childQuestionLayout);
		try {
			if (size > 1) {
				for (int i = 0; i < size; i++) {
					if (i != size - 1 && i == childIndex) {
						View inflate = LayoutInflater.from(getContext()).inflate(R.layout.def_line, mChildLayoutContainer, false);
						LinearLayout.LayoutParams layoutParams = (LayoutParams) inflate.getLayoutParams();
						layoutParams.bottomMargin = (int) getResources().getDimension(R.dimen.dp_10);
						mChildLayoutContainer.addView(inflate);
					}
				}
			}
		} catch (Exception e) {
			Log.e(TAG, "setChildContent:Exception ");
		}


	}

	private LswAnswer createDefaultAnswer(ResourceDetail resourceDetail, Questions childQuestion, String uuid,int bigQuesIndex,int totalQuesIndex,String quesNo) {
		LswAnswer lswAnswer = new LswAnswer();
		lswAnswer.setWorkSaveUUid(uuid);
		if (childQuestion.getType() == Questions.QuestionType.QUESTION_TYPE_CHOICE) {

			lswAnswer.setAnswerType(Questions.AnswerType.QUESTION_TYPE_CHOICE);
		}

		lswAnswer.setVersionId(childQuestion.getVersionId());
		lswAnswer.setUploadState(LswAnswer.SUCCESS);
		List<AnswerContent> answerContents = new ArrayList<AnswerContent>();
		AnswerContent answerContent = new AnswerContent();
		answerContent.setSid(0);
		List<OptionInfo> optionInfos = childQuestion.getOptions();
		//找出正确答案ID  只适用单选
		if (null != optionInfos && optionInfos.size() > 0) {
			for (OptionInfo o : optionInfos) {
				//正确答案
				if (o.getIsAnswer() == 1) {
					answerContent.setRefAnswer(o.getId());
				}
			}
		}
		if(resourceDetail!=null){
			List<QuestionScore> smallQuesScores = resourceDetail.getScores();
			if(smallQuesScores!=null){
				for (QuestionScore q : smallQuesScores) {
					if (q.getQuestionVersionId().equals(childQuestion.getVersionId())) {
						lswAnswer.setRefScore(q.getScore());
					}
				}
			}
		}

		answerContent.setContent("");
		answerContents.add(answerContent);
		lswAnswer.setAnswerContents(answerContents);
		lswAnswer.setBigQuesIndex(bigQuesIndex);
		lswAnswer.setTotalQuesIndex(totalQuesIndex);
		lswAnswer.setQuesNo(quesNo);
		lswAnswer.setAnswer(false);
		mAnswerLinkedHashMap.put(childQuestion.getVersionId(), lswAnswer);
		return lswAnswer;
	}

	public void optionsLayoutRemoveAllViews() {
		imgContainer.removeAllViews();
		imgContainer.setVisibility(GONE);
		mChildLayoutContainer.removeAllViews();
		mChildLayoutContainer.setVisibility(GONE);
	}


	public ArrayList<LswAnswer> getLswAnswersOfSamllQuestions() {
		ArrayList<LswAnswer> lswAnswers = new ArrayList<>();
		if (mAnswerLinkedHashMap.size() <= 0) {
			FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, "mAnswerLinkedHashMap的size为0", "长对话页面");
		}
		Set<Map.Entry<String, LswAnswer>> entries = mAnswerLinkedHashMap.entrySet();
		Iterator<Map.Entry<String, LswAnswer>> iterator = entries.iterator();
		while (iterator.hasNext()) {
			Map.Entry<String, LswAnswer> next = iterator.next();
			LswAnswer lswAnswer = next.getValue();
			lswAnswers.add(lswAnswer);
		}
		if (lswAnswers.size() <= 0) {
			FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, "getLswAnswersOfSamllQuestions lswAnswers的size为0", "长对话页面");
		}
		return lswAnswers;
	}

}
